package com.jmyd.sharding.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5生成文件校验值
 *
 * @author samphin
 * @date 2020/12/19 11:39
 */
@Slf4j
public class MD5Utils {
    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
     */
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static MessageDigest messagedigest = null;

    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error(MD5Utils.class.getName() + "初始化失败，MessageDigest不支持MD5Util。");
        }
    }

    /**
     * 生成字符串的md5校验值
     *
     * @param s 待处理字符串
     * @date 2020-12-19 11:47:07
     */
    public static String encrypt(String s) {
        return encrypt(s.getBytes());
    }

    /**
     * 判断字符串的md5校验码是否与一个已知的md5码相匹配
     *
     * @param sourceStr 要校验的字符串
     * @param md5Value  已知的md5校验码
     */
    public static boolean validate(String sourceStr, String md5Value) {
        String s = encrypt(sourceStr);
        return s.equals(md5Value);
    }

    /**
     * 生成文件的md5校验值
     *
     * @param file 待加密码文件
     */
    public static String encrypt(File file) throws IOException {
        return encrypt(new FileInputStream(file));
    }

    /**
     * 生成文件的md5校验值
     *
     * @param inputStream 待加密码文件流
     */
    public static String encrypt(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int numRead = 0;
        while ((numRead = inputStream.read(buffer)) > 0) {
            messagedigest.update(buffer, 0, numRead);
        }
        inputStream.close();
        return bufferToHex(messagedigest.digest());
    }

    /**
     * @param sourceStr 需要加密的字符串
     * @param isUpper   字母大小写(false为默认小写，true为大写)
     * @param bit       加密的类型（16,32,64)
     * @author samphin
     * @date 2021-3-29 09:30:29
     */
    public static String encrypt(String sourceStr, boolean isUpper, Integer bit) {
        String md5 = null;
        try {
            // 创建加密对象
            MessageDigest md = MessageDigest.getInstance("md5");
            if (bit == 64) {
                BASE64Encoder bw = new BASE64Encoder();
                md5 = bw.encode(md.digest(sourceStr.getBytes(StandardCharsets.UTF_8)));
            } else {
                // 计算MD5函数
                md.update(sourceStr.getBytes());
                byte b[] = md.digest();
                int i;
                StringBuffer sb = new StringBuffer("");
                for (int offset = 0; offset < b.length; offset++) {
                    i = b[offset];
                    if (i < 0)
                        i += 256;
                    if (i < 16)
                        sb.append("0");
                    sb.append(Integer.toHexString(i));
                }
                md5 = sb.toString();
                if (bit == 16) {
                    //截取32位md5为16位
                    md5 = md5.substring(8, 24);
                    if (isUpper){
                        md5 = md5.toUpperCase();
                    }
                    return md5;
                }
            }
            //转换成大写
            if (isUpper) {
                md5 = md5.toUpperCase();
            }
        } catch (Exception e) {
            log.error("md5加密抛出异常！");
        }
        return md5;
    }

    /**
     * 获取type数组的md5值
     *
     * @param bytes
     * @author samphin
     * @date 2020-12-19 11:45:12
     */
    public static String encrypt(byte[] bytes) {
        messagedigest.update(bytes);
        return bufferToHex(messagedigest.digest());
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = HEX_DIGITS[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>
        // 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同
        char c1 = HEX_DIGITS[bt & 0xf];// 取字节中低 4 位的数字转换
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        File file = new File("D:/st1.txt");
        if (!file.exists()) {
            log.info("不存在");
        }
        String md5 = encrypt("123456");
        long end = System.currentTimeMillis();
        log.info("md5:" + md5 + " time:" + ((end - begin) / 1000) + "s");
        log.info(file.getPath());

        String encrypt = encrypt("fjmywcbwg1958");
        System.out.println("encrypt = " + encrypt);
        String encrypt1 = encrypt("123456 ");
        System.out.println("encrypt1 = " + encrypt1);
    }
}
